<template>
  <div class="inner" v-show="toggleShowBox">
    <Transition name="slide">
      <div class="slide" v-show="toggleShow">
        <div class="middle-create-btn" @click="addmagChat">
          <img src="@/assets/img/chat/jiahao.png" alt="添加对话">
          <p>创建对话</p>
        </div>
        <!-- 做个虚拟列表 -->
        <div class="chatlist">

          <chatListArrayAA @delChat="delListApi" @clickChat="clickchatApi" @putChat="putChatId" @getChat="addList"
            :chatListRes="chatListRes" />

        </div>



        <div class="userTokenPay">
          <img src="@/assets/img/userConfig/many2@2x.png" alt="">
          <span>
            余额:{{ account }}
          </span>
          <span @click="goPay" style="color: #c90000;">
            充值
          </span>
        </div>
      </div>
    </Transition>
    <div class="toggle" v-show="isShowClick" @click="toggleContent" ref="toggleRef">
      <img v-show="isShowClick" src="@/assets/img/chat/retract.png" alt="reatact" title="你好">
    </div>
  </div>
</template>

<script lang='ts' setup>
import { onBeforeMount, reactive, ref, watch, watchEffect } from 'vue'
import { useThrottle } from '@/utils/tools';
import { addChat, type IaddchatData, ChatList, type IChatList, delChat, updateChatId } from '@/api/chat';
import{getAccountQuota} from '@/api/account'
import { userInfoStore } from '@/stores/userInfo';
import {useRoute,useRouter} from 'vue-router'

import chatListArrayAA from '@/components/chatListArray/index.vue'
import { ElNotification } from 'element-plus';

const toggleShow = ref(true)
const toggleRef = ref<HTMLElement | null>(null)
const { userInfo } = userInfoStore()
const router = useRouter()
const route = useRoute()


// 点击切换
const toggleContent = ()=>{
  toggleShow.value  = !toggleShow.value
  if (toggleShow.value) {
    // 显示
    toggleRef.value.style.transform = 'translateX(255px) translateY(-25%) rotate(0)'
  } else {
    // 隐藏
    toggleRef.value.style.transform = 'translateX(-12px) translateY(-25%) rotate(180deg)'
  }
}
// 去充值
const goPay = ()=>{
  router.push({ path: 'UserConfig' })
}



// 创建的类型 需要判断
const chatData = reactive<IaddchatData>({
  userId: userInfo.userId,
  type: 1,
})

//增加会话
const addmagChat = async () => {

  if (!userInfo) return

  if (route.name === 'Programmers') {
    router.push({params:{
      chattype: ''
    }})
    return
  }
    chatData.type = route.params.chattype
   try{
     let res = await addChat(chatData)
     if(res.code === 0 ){
      ElNotification({
        type: 'success',
        message: '创建成功'
      })
      router.push({query: { chatId: res.data.chatId } })
      ChatListArray()
     }
   } catch (error) {
    console.log(error);
  }}

  //列表点击操作
const clickchatApi = (eventid:string)=>{
    console.log(eventid);
    router.push({ query: { chatId: eventid } })
}

watch(()=>route.query.chatId,(val,oldval)=>{
  console.log(val,oldval);
  if(val === oldval) return
  chatListRes.value.forEach(v => {  
    v.isPut = false;  
  }); 
})


// 会话编辑
const delListApi = (id:string)=>{
  delChat(id).then(
    (res) => {
      console.log(res);
      if(res.code === 0){
        ElNotification({
          type: 'success',
          message: '删除成功'
        })
        ChatListArray()
      }else{
        console.log('删除失败');
      }
     },
    (rej) => { },
  )
}
const putChatId = (data:{id:string,question:string})=>{
  updateChatId(data).then(
    (res) => {
      console.log(res);
      if(res.code === 0 ){
        ElNotification({
          type:'success',
          message:res.data
        })
      }
    },
    (rej) => {
      console.log(rej);
      
     },
  )
}
  

// 查询聊天列表参数 
const getChatListData = reactive({
  userId: userInfo.userId,
  type:3, //type1今日 2七天内 3总数据
  functionType:1,  
  page:1,
  pageSize:20
})
const chatListRes = ref([])

const isShowClick = ref(true) //显示隐藏按钮

// const clickShow = ref(null)
watch(() => route.params.chattype, (newVal, oldVal) => {
  console.log('route.params.chattype', newVal);
  console.log(typeof newVal);
  getChatListData.page = 1
  if (newVal){
    chatData.type = newVal //更改创建的类型
    getChatListData.functionType = newVal //更改查询的列表
    ChatListArray()
    //隐藏这个列表
    toggleShow.value = true
    isShowClick.value = true
  }else{
    toggleShow.value = false
    isShowClick.value = false
  }


})



// 继续获取聊天列表
const addList = ()=>{
  console.log('接收触底加载');
  getChatListData.page++;
  ChatListArray(false)
}


//获取聊天列表
const ChatListArray = async (isClear:boolean=true)=>{
  const res = await ChatList(getChatListData)
   console.log(res);
  if(res.code === 0 && res.data.length > 0 ){
    // Object.assign(chatListRes, res.data)

      let resList = res.data.map(v => ({ ...v, isPut: false }));
    
 
    if (isClear) {
      chatListRes.value = resList
    }else{
      chatListRes.value.push(...resList);
    }
    router.push({ query: { chatId: chatListRes.value[0].id } })
  }else{
    console.log('获取聊天列表失败');
    // router.push({ path: '/' })
  }
}

// 余额查询
const account = ref(0)
const getAccountQuotaAPI = ()=>{
  getAccountQuota().then(
   (res)=>{
    console.log(res);
      account.value = res.data.totalQuota - res.data.currentBalance
   },
 (err)=>{},
  )
}
//路由鉴权
const toggleShowBox = ref(false)
router.beforeEach((to,from,next)=>{
    // console.log('routerto',to,from);
  if (to.name === 'UserCoufig'){
    toggleShowBox.value = false
  }else{
    toggleShowBox.value = true
  }
  next()
})


// onBeforeRouteUpdate((to, from) => {
//   console.log('router111', to, from);
// })


onBeforeMount(()=>{
  getAccountQuotaAPI()
  ChatListArray()
})

</script>
<style scoped lang='scss'>
.inner {
  position: relative;
  height: 100vh;
  width: auto;
  .slide {
    width: 268px;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 17px;
    box-sizing: border-box;
    background-color: #f8f8fa;

    // 用户Token和充值跳转
    .userTokenPay{
      display: flex;
      height: 46px;
      box-sizing: content-box;
      padding:10px 0 ;      
      width: 100%;
      justify-content:flex-start;
      align-items: center;
      img{
        width: 20px;
        margin:  0 5px;
      }
      span:last-child{
        flex-grow: 1;
        text-align: right;
        cursor: pointer;
        
      }


    }

    .chatlist{
      flex-grow: 1;
      overflow: hidden;
      width: 100%;
    }

    // 添加按钮
    .middle-create-btn {
      width: 100%;
      height: 46px;
      padding: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      background: #c90000;
      border-radius: 8px;
      color: #fff;
      font-size: 19px;
      img {
        width: 12px;
        height: 12px;
        margin-right: 6px;
      }
    }
  }

  .slide-enter-active,
  .slide-leave-active {
    transition: all 0.5s ease;
  }

  .slide-enter-from,
  .slide-leave-to {
    transform: translateX(-100%);
  }

  .slide-enter-to,
  .slide-leave-from {
    transform: translateX(0);
  }

  .toggle {
    position: absolute;
    top: 50%;
    left: 0;
    transition: transform .5s ease;
    transform: translateX(255px) translateY(-25%) rotate(0);
    cursor: pointer;
    z-index: 100; //这里设置多少都没有用

    img {
      position: relative;
      width: 22px;
      height: 22px;
    }
  }
}
</style>
